#include "xml_text.h"
#include <QDir>
#include <QTextStream>

#include <QPushButton>
#include <QLineEdit>
#include <QVBoxLayout>

#include <QTextBrowser>
#include <QDateTime>
#include <QDebug>

namespace  {
const QString FILE_PATH = "D:\\work\\qw_work\\xml\\aaa.xml";
}
TestWidget::TestWidget(QWidget *parent)
    : QWidget(parent)
{
//    QString path = "D:\\work\\qw_work\\xml";
//    QString name = "aaa.xml";
//    CreateXmlFile(path, name);
InitWidget();



}

TestWidget::~TestWidget()
{
}

void TestWidget::CreateXmlFile(const QString &path, const QString &name)
{
    QDir dir(path);
    if (!dir.exists()) {
    }
    QString fileName;
    if (name.contains(".xml")) {
        fileName = path + "\\" + name;
    } else {
        fileName = path + "\\" + name + ".xml";
    }

    QFile file (fileName);
    if (!file.open(QIODevice::WriteOnly)) {
        return;
    }

    // 创建xml
    QDomDocument doc;
    QDomProcessingInstruction title = doc.createProcessingInstruction("xml", "version=\'1.0\' encoding=\'utf-8\'");
    doc.appendChild(title);

    QDomElement root = doc.createElement("root");
    doc.appendChild(root);
    QTextStream textStream(&file);
    doc.save(textStream, 4);
    file.close();
}

void TestWidget::AppendXmlItem(const QString &text)
{
    QFile file(FILE_PATH);
    if (!file.open(QIODevice::ReadOnly)) {
        return;
    }
    QDomDocument doc;
    if (!doc.setContent(&file)) {
        qDebug() << "setContent failt";
        file.close();
        return;
    }
    file.close();

    // 获取当前时间
    QDateTime time = QDateTime::currentDateTime();
    QString currentTime = time.toString("hh-mm");

    QDomElement root = doc.documentElement();
    QDomNodeList rootChilds = root.childNodes();
    bool isFind {false};
    for (int index = 0; index <rootChilds.size(); ++index) {
        QDomNode node = rootChilds.item(index);
        if (!node.isElement()) {
            continue;
        }
        QDomElement element = node.toElement();
        // 找到已经存在的节点
        if (element.attribute("time") == currentTime) {
            QDomElement textElement = doc.createElement("text");
            textElement.appendChild(doc.createTextNode(text));
            element.appendChild(textElement);
            isFind = true;
            break;
        }
    }

    if (!isFind) {
        QDomElement element = doc.createElement("Item");
        element.setAttribute("time", currentTime);
        QDomElement textElement = doc.createElement("text");
        textElement.appendChild(doc.createTextNode(text));
        element.appendChild(textElement);

        root.appendChild(element);
    }

    if (!file.open(QIODevice::WriteOnly)) {
        file.close();
        return;
    }

    QTextStream textStream(&file);
    doc.save(textStream, 4);
    file.close();
}

void TestWidget::DeleteXmlItem(const QString &inPutText)
{
    QFile file(FILE_PATH);
    if (!file.open(QIODevice::ReadOnly)) {
        return;
    }
    QDomDocument doc;
    if (!doc.setContent(&file)) {
        qDebug() << "setContent failt";
        file.close();
        return;
    }
    file.close();
    QDomElement root = doc.documentElement();
    QDomNodeList childrenList = root.childNodes();
    for (int index = 0; index < childrenList.size(); index++) {
        QDomNode node = childrenList.item(index);
        if (!node.isElement()) {
            continue;
        }
        QDomElement element = node.toElement();
        qDebug() << "----------------------- " <<inPutText << element.attribute("time");
        if (element.hasAttribute("time") &&element.attribute("time") == inPutText) {

            root.removeChild(node);
        }
    }

    if (!file.open(QIODevice::WriteOnly)) {
        file.close();
        return;
    }

    QTextStream textStream(&file);
    doc.save(textStream, 4);
    file.close();
}

void TestWidget::EditXmlItem(const QString &inPutText)
{
    QFile file(FILE_PATH);
    if (!file.open(QIODevice::ReadOnly)) {
        return;
    }
    QDomDocument doc;
    if (!doc.setContent(&file)) {
        qDebug() << "setContent failt";
        file.close();
        return;
    }
    file.close();
    QDomElement root = doc.documentElement();
    QDomNodeList childrenList = root.childNodes();
    for (int index = 0; index < childrenList.size(); index++) {
        QDomNode node = childrenList.item(index);
        if (!node.isElement()) {
            continue;
        }
        QDomElement element = node.toElement();
//        qDebug() << "----------------------- "  << element.tagName();
        if (element.hasAttribute("time") &&element.attribute("time") == inPutText && element.tagName() == "Item") {
//            element.setTagName("change");
//            element.setAttribute("time", " current time");
//            element.setAttribute("abcdef", " current time");
            if (element.hasChildNodes()) {
                QDomElement firstNode = element.firstChildElement();
                if (!firstNode.isNull()) {
                    firstNode.setTagName("123456");


                    if (firstNode.firstChild().isText()) {
                        QDomText textElement = firstNode.firstChild().toText();
                        qDebug() << " ================= " <<textElement.data();
                        textElement.setData("ppppppppppppppp");
                    }

                }
            }
//            root.removeChild(node);
        }
//        if (element.text()) {

//            root.removeChild(node);
//        }
    }

    if (!file.open(QIODevice::WriteOnly)) {
        file.close();
        return;
    }

    QTextStream textStream(&file);
    doc.save(textStream, 4);
    file.close();
}

void TestWidget::FindXmlItem(QDomDocument &doc, QDomElement &parent, QDomElement &target)
{

}

void TestWidget::InitWidget()
{
    QVBoxLayout *mainVbox = new QVBoxLayout;

    QGridLayout *grid = new QGridLayout;
    QLineEdit *edit = new QLineEdit;
    QPushButton *button = new QPushButton("ok");
    grid->addWidget(edit, 0, 0);
    grid->addWidget(button, 0, 1);

    QLineEdit *editEdlete = new QLineEdit;
    QPushButton *buttonDelete = new QPushButton("delete");
    grid->addWidget(editEdlete, 1, 0);
    grid->addWidget(buttonDelete, 1, 1);

    QLineEdit *editFind = new QLineEdit;
    QPushButton *buttonFind = new QPushButton("find");
    grid->addWidget(editFind, 2, 0);
    grid->addWidget(buttonFind, 2, 1);

    browser_ = new QTextBrowser;
    grid->addWidget(browser_, 3, 0, 2, 1);
    this->setLayout(grid);

    // 添加一个节点
    connect(button, &QPushButton::clicked, [edit, this] () {
        QString text = edit->text();
        AppendXmlItem(text);
        FrushXml();
    });
    // 删除一个节点
    connect(buttonDelete, &QPushButton::clicked, [editEdlete, this] () {
        QString text = editEdlete->text();
        DeleteXmlItem(text);
        FrushXml();
    });
    // 找到一个节点
    connect(buttonFind, &QPushButton::clicked, [editFind, this] () {
        QString text = editFind->text();
        EditXmlItem(text);
//        FrushXml();
    });
}

void TestWidget::FrushXml()
{
    QFile file(FILE_PATH);
    if (!file.open(QIODevice::ReadOnly)) {
        return;
    }

    QDomDocument doc;
    if (!doc.setContent(&file)) {
        file.close();
        return;
    }
    file.close();

    browser_->setText(doc.toString(4));
}

